package com.novellotus.iov.carvice.retrofit;

import android.content.Context;
import android.util.Log;

import com.novellotus.iov.carvice.utils.MyUtils;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Rich on 2017/8/3.
 */

public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {

    private int code;

    protected BaseObserver(Context context) {
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseEntity<T> value) {
        if (value.isSuccess()) {
            T t = null;
            try {
                t = value.getData();
            } catch (Exception e) {
                e.printStackTrace();
            }
            onSuccess(t);
        } else {
            code = value.getCode();
            MyUtils.logInformation(value.getMsg());
            onFail(value.getCode(), value.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        /**
         * e instanceof ConnectException ||
         e instanceof SocketTimeoutException ||
         e instanceof TimeoutException
         * */
        MyUtils.logInformation(code + "");
        if (MyUtils.isTimeOut(e.toString())) {
            onError("链接超时");
        } else if (MyUtils.isIllegalState(e.toString())) {
            onError("数据异常");
        } else if (e instanceof ResultException) {
            //自定义的ResultException
            //由于返回200,300返回格式不统一的问题，自定义GsonResponseBodyConverter凡是300的直接抛异常
            onError(((ResultException) e).getCode() + "");
        } else {
            onError("网络异常");
        }

    }

    @Override
    public void onComplete() {
    }

    public abstract void onSuccess(T t);

    public abstract void onFail(int code, String msg);

    public abstract void onError(String msg);
}
